#!/usr/bin/env python
# -*- coding:utf-8 -*-
'''
@FileName  :SerialChartDisplay.py 
@desc      :
@Author    :Young
@IDE       :PyCharm
@Time      :2022-10-25 9:27
'''

from PyQt5 import QtWidgets
from PyQt5.QtChart import QDateTimeAxis,QValueAxis,QSplineSeries,QChart,QChartView
from PyQt5.QtWidgets import QApplication
from PyQt5.QtGui import QPainter
from PyQt5.QtCore import QDateTime,Qt,QTimer
import time
import serial
import serial.tools.list_ports
import sys
import random



def open_port(port, bps, timeout):  # 打开串口
    ret = False
    #print(6666666)
    try:
        # 打开串口，并得到串口对象
        ser = serial.Serial(port, bps, timeout=timeout)
        # 判断是否打开成功
        if ser.is_open:
            ret = True
            print("打开串口操作成功！")
            print(port + "打开了")
    except Exception as e:
        print("---异常---：", e)
    return ret, ser

class PyqtChart_Serial(QChartView, QChart):
    def __init__(self):
        super(PyqtChart_Serial, self).__init__() # **
        self.receivePort = None  # 接收串口
        self.receiveCondition = False  # 接收串口状态
        self.resize(1200, 600)
        self.setRenderHint(QPainter.Antialiasing)  # 抗锯齿
        self.addN = 1
        self.chart_init()
        self.timer_init()
        self.open_receive_port()  #打开串口

    def timer_init(self):
        #使用QTimer，2秒触发一次，更新数据
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.drawLine)
        self.timer.start(2000)

    def chart_init(self):
        self.chart = QChart()
        self.series = QSplineSeries()
        self.series1 = QSplineSeries()
        #设置曲线名称
        self.series.setName("温度数据")
        self.series1.setName("光照数据")
        #把曲线添加到QChart的实例中
        self.chart.addSeries(self.series)
        self.chart.addSeries(self.series1)
        #声明并初始化X轴，Y轴
        self.dtaxisX = QDateTimeAxis()
        self.vlaxisY = QValueAxis()
        #设置坐标轴显示范围
        self.dtaxisX.setMin(QDateTime.currentDateTime().addSecs(-300*1))
        self.dtaxisX.setMax(QDateTime.currentDateTime().addSecs(0))
        self.vlaxisY.setMin(0)
        self.vlaxisY.setMax(30)
        #设置X轴时间样式
        self.dtaxisX.setFormat("MM月dd hh:mm:ss")
        #设置坐标轴上的格点
        self.dtaxisX.setTickCount(6)
        self.vlaxisY.setTickCount(21)
        #设置坐标轴名称
        self.dtaxisX.setTitleText("时间")
        self.vlaxisY.setTitleText("温度/光照")
        #设置网格显示
        self.vlaxisY.setGridLineVisible(True)
        #把坐标轴添加到chart中
        self.chart.addAxis(self.dtaxisX,Qt.AlignBottom)
        self.chart.addAxis(self.vlaxisY,Qt.AlignLeft)
        #把曲线关联到坐标轴
        self.series.attachAxis(self.dtaxisX)
        self.series.attachAxis(self.vlaxisY)
        self.series1.attachAxis(self.dtaxisX)
        self.series1.attachAxis(self.vlaxisY)

        self.setChart(self.chart)


    def reset(self):
        '''
        Reset按钮对应函数，完成接收端口的关闭，及接收串口数据的清除
        :return:
        '''
        self.close_receive_port()
        self.clear_receive()

    def open_receive_port(self):
        '''
        打开接收端口
        :return:
        '''
        port = 'COM3'  # 接收接口的名字
        bps = 9600  # 接受接口的波特率
        timeout = None  # 接收接口的连接时间
        # print(2222222)
        self.receiveCondition, self.receivePort = open_port(port, bps, timeout)

    def close_receive_port(self):
        '''
        关闭数据接收端口
        :return: None
        '''
        try:
            # 判断是否打开成功
            if self.receivePort.is_open:
                self.receivePort.close()  # 关闭数据接收端口
                self.receiveCondition = False  # 更新接收端口状态
        except Exception as e:
            print("---异常---：", e)

    def start_receive_temp_and_illumination_info(self):
        '''
        用于接收温度和光照信息
        :return:
        '''
        print("开始接收温度和光照信息……")
        if self.receiveCondition:
            print("温度光照信息连接已经建立！")
            # T24I1X
            while(True):
                text = self.receivePort.read(16).decode("gbk")
                print(text)  # 对text进行解析，传数据库，展示
                self.receivePort.flushInput() #清除缓存数据
                time.sleep(2) #延迟两秒
                # print(111111111111111)
                self.analyseData(text)
                self.displayData()

    def drawLine(self):
        '''
        画出实时曲线图
        :return:
        '''
        #获取当前时间
        bjtime = QDateTime.currentDateTime()
        #更新X轴坐标
        self.dtaxisX.setMin(QDateTime.currentDateTime().addSecs(-300*1))
        self.dtaxisX.setMax(QDateTime.currentDateTime().addSecs(0))
        #当曲线上的点超出X轴的范围时，移除最早的点
        if(self.series.count()>149):
            self.series.removePoints(0,self.series.count()-149)

        #读取串口的数据，解析数据，变成yint和yint1,关闭串口
        print("开始接收温度和光照信息……")
        #确立连接状态，若连接正确建立则接收数据->清理缓冲取
        if self.receiveCondition:
            print("温度光照信息连接已经建立！")
            text = self.receivePort.read(5).decode('gbk')
            self.receivePort.flushInput()  # 清除缓存数据
            print(text)
            #24XLX
            x1 = text[0:2]  #温度数据
            print("len",len(text.strip()))
            x2 = text[3:4]  #光照数据
            if(x1 == "00"):
                x1 = "0"

            print("x2",x2)
            if(x2 == "L"):
                x3 = 1
            else:
                x3 = 0
            # print("x3",x3)
            # print(int(x1))

            # yint = random.randint(0, 30)
            # yint1 = random.randint(0, 1)
            # 添加数据到曲线末端
            self.series.append(bjtime.toMSecsSinceEpoch(), int(x1))
            self.series1.append(bjtime.toMSecsSinceEpoch(), int(x3))

import sys
if __name__=='__main__':
    app =  QtWidgets.QApplication(sys.argv)
    drawChartWindow = PyqtChart_Serial()
    drawChartWindow.show()
    sys.exit(app.exec_())
